import React, { Component } from 'react'
import Routes from '../../router/admin'
import { Button, Layout, Menu, message, Modal } from 'antd'
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  // UploadOutlined,
  // UserOutlined,
  // VideoCameraOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
// 引入css
import '../../assets/css/layout.css'
// import { Link } from 'react-router-dom'
// 加载组件
// import Welcome from './Welcome'
// import UserList from './users/Index'
// import UserAdd from './users/Add'
import url from '../../config/url'
import req from '../../http/req'
const { Header, Sider, Content } = Layout
// const { SubMenu } = Menu
export default class Index extends Component {
  constructor(props) {
    super(props)
    // 默认选中菜单  根据url地址 匹配菜单中的key
    this.defaultSelectedKeys = [this.props.location.pathname]
    // 展开菜单  根据url地址  匹配菜单中的key
    // 选中的是子菜单  展开的父菜单
    // /dashboard/user/index 处理为 /dashboard/user
    this.defaultOpenKeys = [
      '/' + this.props.location.pathname.split('/').splice(1, 2).join('/')
    ]
    // 通过校验确定是否登录,如果登录就修改isLogin状态为true
    req.get(url.PreCheck).then((res) => {
      // console.log(res);
      // 校验登录通过
      if (res.data.errNo === 0) {
        this.setState({ isLogin: true })
      } else {
        // 未登录 清除token acl
        localStorage.removeItem('jwt')
        localStorage.removeItem('acl')
        message.error('未登录,请登录')
        this.props.history.push('/login')
      }
    })
  }
  state = {
    collapsed: false,
    adminInfo: { last_login_addr: {} },
    // 记录用户是否登录的状态
    isLogin: false
  }
  // 类组件的数据存储在类属性还是state中
  // 不变的数据可以存储在类属性中,需要改变的数据存储在state中
  acl = JSON.parse(localStorage.getItem('acl'))
  componentDidMount() {
    req.get(url.GetAdminInfo).then((res) => {
      // console.log(res);
      this.setState({ adminInfo: res.data.accountInfo })
    })
  }
  componentDidUpdate() {
    // console.log(this.props.location.pathname);
    this.defaultSelectedKeys = [this.props.location.pathname]
    this.defaultOpenKeys = [
      '/' + this.props.location.pathname.split('/').splice(1, 2).join('/')
    ]
    // this.setState({})
  }
  render() {
    if (this.state.isLogin === false) {
      return <></>
    }
    const { collapsed, adminInfo } = this.state
    return (
      <Layout style={{ height: '100%' }}>
        <Sider trigger={null} collapsible collapsed={collapsed}>
          <div className="logo" />
          {/* 4.20版本以前的标签写法 */}
          {/* <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
            {this.acl.map((item) => {
              if (item.children.length === 0) {
                return (
                  <Menu.Item key={item.auth_path}>
                    <Link to={item.auth_path}>{item.auth_name}</Link>
                  </Menu.Item>
                )
              } else {
                return (
                  <SubMenu key={item.auth_path} title={item.auth_name}>
                    {item.children.map((el) => {
                      if (el.is_nav === 1) {
                        return (
                          <Menu.Item key={el.auth_path}>
                            <Link to={el.auth_path}>{el.auth_name}</Link>
                          </Menu.Item>
                        )
                      }
                    })}
                  </SubMenu>
                )
              }
            })}
          </Menu> */}
          <Menu
            theme="dark"
            mode="inline"
            // 默认选中的菜单
            defaultSelectedKeys={this.defaultSelectedKeys}
            // 默认打开的菜单
            defaultOpenKeys={this.defaultOpenKeys}
            // 4.20以上版本写法 items 数组 元素是对象
            items={this.parseItems()}
          />
        </Sider>
        <Layout className="site-layout">
          <Header
            className="site-layout-background"
            style={{
              padding: 0
            }}
          >
            {React.createElement(
              collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
              {
                className: 'trigger',
                onClick: () => this.setState({ collapsed: !collapsed })
              }
            )}
            <span>
              您好,{adminInfo.username} ({adminInfo.role}) ！ 您的账号上次于
              {adminInfo.last_login_addr.state}/{adminInfo.last_login_addr.isp}[
              {adminInfo.last_ip}]登录！
              <Button type="primary" size="small" onClick={this.logout}>
                退出
              </Button>
            </span>
          </Header>
          <Content
            className="site-layout-background"
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280
            }}
          >
            {/* 渲染组件 */}
            <Routes />
          </Content>
        </Layout>
      </Layout>
    )
  }
  logout = () => {
    // 通过confirm判断是否退出登录
    Modal.confirm({
      title: '退出登录',
      icon: <ExclamationCircleOutlined />,
      content: '确认退出吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 注销退出登录
        // 1、删除用户存储的信息  jwt  acl(菜单)
        localStorage.removeItem('jwt')
        localStorage.removeItem('acl')
        // 2、跳转回到登录页面
        message.success('退出成功')
        this.props.history.push('/login')
      }
    })
  }
  // 处理acl菜单数据并显示到页面上
  parseItems() {
    let items = []
    // console.log(this.acl)
    this.acl.forEach((item) => {
      // 每一个菜单
      let obj = {}
      obj['label'] = item.auth_name
      obj['key'] = item.auth_path
      if (item.auth_path === '/dashboard/welcome') {
        obj['onClick'] = () => {
          this.props.history.push(item.auth_path)
        }
      }
      // 子菜单数组长度不为0 具有子菜单
      if (item.children.length > 0) {
        obj['children'] = []
        item.children.forEach((el) => {
          // 判断为菜单再显示
          if (el.is_nav === 1) {
            obj['children'].push({
              label: el.auth_name,
              key: el.auth_path,
              onClick: () => {
                this.props.history.push(el.auth_path)
              }
            })
          }
        })
      }
      items.push(obj)
    })
    // console.log(items)
    return items
  }
}
